<template>
  <div>
    <div class="curr-page">
      <!-- 面包屑 -->
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>车辆详情</el-breadcrumb-item>
        <el-breadcrumb-item>{{ page_title }}</el-breadcrumb-item>
      </el-breadcrumb>

      <!-- 渲染内容 -->
      <el-tabs
        type="border-card"
        style="margin-top:20px"
        v-model="init_tab_show"
      >
        <el-tab-pane label="车辆基本信息" name="first">
          <div class="car-content">
            <div class="car-left">
              <div class="car-icon">
                <img :src="show_obj.icon" style="height:320px;width:460px" />
              </div>
            </div>
            <div class="car-right">
              <div class="car-name">
                {{ show_obj.name }}
              </div>

              <!-- 价格 -->
              <div class="car-price">{{ show_obj.price }} 万元</div>

              <!-- 里程，车龄等信息 -->
              <div class="middle-content">
                <div class="car-milage">
                  行驶里程：
                  {{ show_obj.milage }}
                </div>
                <div class="car-age">
                  车龄：
                  {{ show_obj.age }}
                </div>
                <div class="car-age">
                  燃油类型：
                  {{ show_obj.TransmissionType }}
                </div>
              </div>

              <!-- 收藏预约按钮 -->
              <div style="margin-left: 100px;margin-top:30px">
                <div v-if="!isCarHost" class="d-flex ai-center">
                  <!-- 预约 -->
                  <div class="mr-5">
                    <!-- 未预约，进行预约 -->
                    <el-button
                      type="success"
                      @click="openDialog"
                      v-show="connect_state == -1"
                      round
                    >
                      预约看车
                    </el-button>

                    <!-- 已预约，取消预约 -->
                    <el-button
                      type="primary"
                      @click="cancalConnect"
                      round
                      v-show="connect_state == 0"
                    >
                      正在预约
                    </el-button>

                    <!-- 预约失败 -->
                    <el-button
                      type="success"
                      @click="openDialog"
                      v-show="connect_state == 1"
                      round
                    >
                      预约失败，再次预约
                    </el-button>

                    <!-- 预约成功 -->
                    <span v-show="connect_state == 2" class="text-red"
                      >预约成功</span
                    >
                  </div>

                  <!-- 收藏 -->
                  <div @click="operationCarCollect">
                    <el-button
                      round
                      v-if="collect_status"
                      style="background-color:#ddd"
                    >
                      已收藏
                      <i class="el-icon-check ml-1"></i
                    ></el-button>
                    <el-button round type="warning" v-else> 添加收藏</el-button>
                  </div>
                </div>
                <div v-else>
                  当前车辆你是车主
                </div>
              </div>
            </div>
          </div>
        </el-tab-pane>

        <el-tab-pane label="车辆详细图片" name="second">
          <div v-if="detailPics.length == 0">
            <el-empty description="暂无图片描述信息"></el-empty>
          </div>

          <el-row type="flex" style="flex-wrap:wrap" v-else>
            <div
              v-for="(detailPicsItem, carIndex) in detailPics"
              :key="carIndex"
            >
              <div label="名称" style="font-size:16px">
                {{ detailPicsItem.name }} : {{ detailPicsItem.description }}
              </div>
              <div class="car-icon">
                <img
                  :src="detailPicsItem.icon"
                  style="height:320px;width:460px;margin-right:30px"
                />
              </div>
            </div>
          </el-row>
        </el-tab-pane>
      </el-tabs>

      <!-- dialog 预约车辆对话框 -->
      <el-dialog
        v-model="showConnectDialog"
        title="预约表单"
        width="50%"
        destroy-on-close
      >
        <!-- 表单 -->
        <el-form
          :model="form"
          :rules="rules"
          :inline="false"
          size="normal"
          label-width="80px"
          ref="form"
        >
          <el-form-item label="预约日期" size="normal" prop="date">
            <el-date-picker
              v-model="form.date"
              type="date"
              placeholder="选择日期"
            >
            </el-date-picker>
          </el-form-item>

          <el-form-item label="预约时间" size="normal" prop="time">
            <el-time-select
              v-model="form.time"
              start="08:30"
              step="00:15"
              end="18:30"
              placeholder="选择时间"
            >
            </el-time-select>
          </el-form-item>

          <el-form-item label="预约留言" prop="message">
            <el-input
              v-model="form.message"
              type="textarea"
              :rows="2"
            ></el-input>
          </el-form-item>
        </el-form>

        <template #footer>
          <span>
            <el-button @click="showConnectDialog = false" size="mini"
              >取 消</el-button
            >
            <el-button type="primary" @click="addConnect" size="mini"
              >确 定</el-button
            >
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>
export default {
  props: {
    id: {},
  },

  data() {
    return {
      show_obj: {},
      page_title: "",
      detailPics: {},

      init_tab_show: "first",

      // 收藏
      collect_status: false,
      collect_id: null,

      // 预约
      showConnectDialog: false,
      connect_state: -1,
      connect_id: null,
      rules: {
        date: [{ required: true, message: "请输入", trigger: "blur" }],
      },
      form: {},
    };
  },

  computed: {
    username() {
      return sessionStorage.username;
    },

    userId() {
      return sessionStorage.userId;
    },

    isCarHost() {
      if (sessionStorage.userId == this.show_obj.userId) {
        return true;
      } else {
        return false;
      }
    },
  },
  methods: {
    // 页面初始化内容占位
    fetchInitData() {
      this.fetchShowObj();
    },

    // 获取渲染对象内容
    async fetchShowObj() {
      await this.$axios.get(`/car/${this.id}`).then((res) => {
        console.log(res);
        this.show_obj = res.data;
        this.page_title = this.show_obj.name;
        this.detailPics = this.show_obj.detailPics;
      });
      this.fetchUserIsConnect();
    },

    // 打开dialog ，填写预约信息
    openDialog() {
      if (sessionStorage.userId) {
        this.showConnectDialog = true;
      } else {
        this.$message({
          type: "warning",
          message: "你未登录，请登录",
        });
      }
    },

    // 用户预约
    async addConnect() {
      // 警告
      this.$confirm(
        "预约看车，一旦预约成功不能修改，请谨慎操作,是否确认？",
        "确认信息",
        {
          distinguishCancelAndClose: true,
          confirmButtonText: "确认",
          cancelButtonText: "放弃",
        }
      )
        // 确认
        .then(async () => {
          // 发起预约请求
          this.form.fromId = sessionStorage.userId;
          this.form.toId = this.show_obj.userId;
          this.form.carId = this.show_obj._id;
          console.log(this.form);

          await this.$axios
            .post("/connect", this.form)
            .then((data) => {
              console.log(data);
              this.showConnectDialog = false;
              this.$message({
                type: "success",
                message: "预约成功",
              });
              this.fetchUserIsConnect();
            })
            .catch(() => {
              this.$message({
                type: "danger",
                message: "失败",
              });
            });
        })
        // 取消
        .catch((action) => {
          this.$message({
            type: "info",
            message:
              action === "cancel" ? "放弃保存并离开页面" : "停留在当前页面",
          });
        });
    },

    // 取消预约
    async cancalConnect() {
      // 警告
      this.$confirm("取消预约,是否确认？", "确认信息", {
        distinguishCancelAndClose: true,
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      })
        // 确认
        .then(async () => {
          // 发起取消请求
          this.$axios.delete(`/connect/${this.connect_id}`).then(() => {
            this.fetchUserIsConnect();
          });

          this.$message({
            type: "info",
            message: "取消成功",
          });
        })
        // 取消
        .catch((action) => {
          this.$message({
            type: "info",
            message: action === "cancel" ? "放弃取消" : "关闭页面",
          });
        });
    },

    // 查看当前 用户的是否预约当前车辆
    async fetchUserIsConnect() {
      if (sessionStorage.userId)
        this.$axios
          .get("/connect/is_connect", {
            params: {
              fromId: sessionStorage.userId,
              toId: this.show_obj.userId,
              carId: this.show_obj._id,
            },
          })
          .then((res) => {
            console.log(res);
            if (res.data.is_connect) {
              this.connect_state = res.data.state;
              this.connect_id = res.data.data._id;
            } else {
              this.connect_id = null;
              this.connect_state = -1;
            }
          });
    },

    // 收藏车辆
    async operationCarCollect() {
      if (sessionStorage.userId) {
        if (this.collect_status) {
          // 已经收藏，取消收藏
          await this.$http.delete(`/user/collects/${this.collect_id}`);
          this.$message({ message: "取消收藏成功", type: "success" });
          this.collect_status = false;
        } else {
          // 未收藏，添加收藏
          const res = await this.$http.post("/collect", {
            userId: sessionStorage.userId,
            collectId: this.id,
            collectType: "车辆",
          });
          this.collect_id = res._id;
          this.$message({
            message: "收藏成功",
            type: "success",
            duration: 800,
          });
          this.collect_status = true;
        }
      } else {
        this.$confirm("你当前暂未登录，是否登录?", "提示", {
          confirmButtonText: "前往登录",
          cancelButtonText: "我再看看",
          type: "warning",
        })
          .then(() => {
            this.$router.push("/login");
          })
          .catch(() => {});
      }
    },

    async fetchCollectStatus() {
      const res = await this.$http.get(`/collect`, {
        params: {
          userId: sessionStorage.userId,
          collectId: this.id,
          collectType: "车辆",
        },
      });
      if (res.message == "success") {
        this.collect_id = res._id;
        this.collect_status = true;
      }
    },
  },

  created() {
    this.fetchInitData();
  },
};
</script>

<style lang="scss" scoped>
.curr-page {
  width: 1080px;
  margin: 0 auto;
  padding-top: 30px;
}
.car-left {
  flex-wrap: wrap;
}
.car-content {
  flex-wrap: wrap;
  display: flex;
  margin: 20 auto;
  width: 1080px;
  left: 10px;
}
.car-right {
  display: block;
  flex-wrap: wrap;
  display: flex;
  flex-direction: column;
  margin-top: 25px;
}

.middle-content {
  background-color: fixed;
  -color: rgba(223, 107, 107, 0.671);
  display: block;
  margin-top: 20px;
  margin-left: 100px;
  flex-direction: column;
  font-size: 13px;
}
.car-age {
  margin-top: 15px;
}

.car-name {
  flex-wrap: wrap;
  display: flex;
  margin: 10px 0;
  margin-left: 100px;
  font-size: 16px;
}
.car-price {
  flex-wrap: wrap;
  display: block;
  font-size: 25px;
  color: red;
  margin-bottom: 15px;
  margin-left: 100px;
  margin-top: 20px;
}
.car-icon {
  margin: 10px 0;
  font-size: 6px;
}
</style>
